package com.sz.mes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.vo.JsonResult;
import com.sz.mes.entity.*;
import com.sz.mes.mapper.*;
import com.sz.mes.service.CastMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.awt.event.FocusEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import java.util.stream.Collectors;

/**
* 投料相关Service实现
* @author hem
* @version 1.0
* @date 2024-01-19
 * Copyright © szhs
*/
@Service
@Slf4j
public class CastMaterialServiceImpl extends BaseCustomServiceImpl<CastMaterialMapper, CastMaterial> implements CastMaterialService {

    private final TechniqueMapper techniqueMapper;
    private final TechMapper techMapper;
    private final OutboundMapper outboundMapper;
    private final CastMaterialMapper castMaterialMapper;
    private final OutputMapper outputMapper;

    public CastMaterialServiceImpl(TechniqueMapper techniqueMapper, TechMapper techMapper, OutboundMapper outboundMapper, CastMaterialMapper castMaterialMapper, OutputMapper outputMapper) {
        this.techniqueMapper = techniqueMapper;
        this.techMapper = techMapper;
        this.outboundMapper = outboundMapper;
        this.castMaterialMapper = castMaterialMapper;
        this.outputMapper = outputMapper;
    }


    @Override
    public JsonResult findUsableMaterial(String taskNum, String techName) {
        QueryWrapper<Tech> tqw = new QueryWrapper<>();
        tqw.eq("task_num",taskNum);
        tqw.eq("is_deleted",0);
        List<Tech> techList = techMapper.selectList(tqw);

        QueryWrapper<Technique> tqqw = new QueryWrapper<>();
        tqqw.eq("task_num",taskNum);
        List<Technique> one = techniqueMapper.selectList(tqqw);

        tqqw.eq("tech_name",techName);
        List<Technique> techniques = techniqueMapper.selectList(tqqw);

//        List<String> techNameList = techList.stream().collect(Collectors.groupingBy(Tech::getTechName))
//                .entrySet().stream().map(Map.Entry::getKey).collect(Collectors.toList());
        ArrayList<String> techNameList = new ArrayList<>();
        for (Tech tech:techList){
            techNameList.add(tech.getTechName());
        }
        int indexOf = techNameList.indexOf(techName);

        //如果是第一道工序
        //当前工序为设计工序第一道||跳过第一道数据
        if ( techName.equals(techList.get(0).getTechName()) || one.size() == 1 || techName.equals(one.get(0).getTechName())){
            QueryWrapper<Outbound> oqw = new QueryWrapper<>();
            oqw.eq("task_num",taskNum);
            List<Outbound> outbounds = outboundMapper.selectList(oqw);
            if (outbounds.size() != 0 && !outbounds.isEmpty()){
                int sum = outbounds.stream().map(o -> new Integer(o.getQuantity())).mapToInt(Integer::intValue).sum();

                if (techniques != null){
                    //第一道工序投过料，把投过的减去
                    int cast=0;
                    for (Technique technique:techniques) {
                        QueryWrapper<CastMaterial> cqw = new QueryWrapper<>();
                        cqw.eq("tech_id", technique.getId());
                        List<CastMaterial> castMaterials = castMaterialMapper.selectList(cqw);
                        cast += castMaterials.stream().map(o -> new Integer(o.getCastQuantity())).mapToInt(Integer::intValue).sum();
                    }
                    return JsonResult.OK(sum - cast);
                }else {
                    return JsonResult.OK(sum);
                }
            }else {
                return JsonResult.FAIL_EXCEPTION("没有领料");
            }
        }else {
            //第二道设计工序往后
            Technique lastTechnique = new Technique();
            //栈，排列后先建的工序在后面，下标0是最后一道工序
            for( int i=indexOf ; i >=0 ; i-- ){
                int a=i;
                String lastTechName = techNameList.get(i-1);
                QueryWrapper<Technique> ltqw = new QueryWrapper<>();
                ltqw.eq("task_num",taskNum);
                ltqw.eq("tech_name",lastTechName);
                lastTechnique = techniqueMapper.selectOne(ltqw);
                if (lastTechnique != null){
                    break;
                }
            }
//            for( int i=indexOf ; i < techNameList.size()-1 ; i++ ){
//                int a=i;
//                String lastTechName = techNameList.get(i+1);
//                QueryWrapper<Technique> ltqw = new QueryWrapper<>();
//                ltqw.eq("task_num",taskNum);
//                ltqw.eq("tech_name",lastTechName);
//                lastTechnique = techniqueMapper.selectOne(ltqw);
//                if (lastTechnique != null){
//                    break;
//                }
//            }
            QueryWrapper<Output> oqw = new QueryWrapper<>();
            oqw.eq("tech_id",lastTechnique.getId());
            List<Output> outputList = outputMapper.selectList(oqw);
            if (outputList.size() != 0 && !outputList.isEmpty()){
                int goodsum = outputList.stream().map(o -> new Integer(o.getGoodQuantity())).mapToInt(Integer::intValue).sum();
                int badsum = outputList.stream().map(o -> new Integer(o.getBadQuantity())).mapToInt(Integer::intValue).sum();
                int cast=0;
                for (Technique technique:techniques) {
                    QueryWrapper<CastMaterial> cqw = new QueryWrapper<>();
                    cqw.eq("tech_id", technique.getId());
                    List<CastMaterial> castMaterials = castMaterialMapper.selectList(cqw);
                    cast += castMaterials.stream().map(o -> new Integer(o.getCastQuantity())).mapToInt(Integer::intValue).sum();
                }

//                if (castMaterials.size() !=0 && !castMaterials.isEmpty()){
                    return JsonResult.OK(goodsum+badsum-cast);
//                }else {
//                    return JsonResult.OK(goodsum+badsum);
//                }
            }else {
                return JsonResult.FAIL_EXCEPTION("上道工序没有产出");
            }

        }
    }

    @Override
    public JsonResult findDetail(String taskNum) {
        QueryWrapper<Technique> tqw = new QueryWrapper<>();
        tqw.eq("task_num",taskNum);
        List<Technique> techniqueList = techniqueMapper.selectList(tqw);
        List<CastMaterial> castMaterialList=new ArrayList<>();
        for (Technique t:techniqueList){
            QueryWrapper<CastMaterial> cqw = new QueryWrapper<>();
            cqw.eq("tech_id",t.getId());
            List<CastMaterial> list = castMaterialMapper.selectList(cqw);
            castMaterialList.addAll(list);
        }

        return JsonResult.OK(castMaterialList);
    }

    @Override
    public JsonResult findCastMaterial(Long techId) {
        QueryWrapper<CastMaterial> cqw = new QueryWrapper<>();
        cqw.eq("tech_id",techId);
        cqw.eq("is_used",1);
        List<CastMaterial> castMaterialList1 = castMaterialMapper.selectList(cqw);

        QueryWrapper<CastMaterial> qw = new QueryWrapper<>();
        qw.eq("tech_id",techId);
        qw.eq("is_used",0);
        List<CastMaterial> castMaterialList2 = castMaterialMapper.selectList(qw);

        QueryWrapper<Output> oqw = new QueryWrapper<>();
        oqw.eq("tech_id",techId);
        List<Output> outputList = outputMapper.selectList(oqw);
        int goodsum = outputList.stream().map(o -> new Integer(o.getGoodQuantity())).mapToInt(Integer::intValue).sum();
        int badsum = outputList.stream().map(o -> new Integer(o.getBadQuantity())).mapToInt(Integer::intValue).sum();
        int old = 0;
        int lastest = 0;
        if ( castMaterialList1 != null && castMaterialList1.size() != 0 ){
            old = castMaterialList1.stream().map(o -> new Integer(o.getCastQuantity())).mapToInt(Integer::intValue).sum();
        }
        if ( castMaterialList2 != null && castMaterialList2.size() != 0 ){
            lastest= castMaterialList2.stream().map(o -> new Integer(o.getCastQuantity())).mapToInt(Integer::intValue).sum();
        }

        //第一次投料
        if ( castMaterialList1.size() == 0 && castMaterialList2.size() == 1 ){
            return JsonResult.OK(lastest);
        }else {
            return JsonResult.OK(old-(goodsum+badsum)+lastest);
        }

    }

    @Override
    public JsonResult insert(CastMaterial entity) {
        QueryWrapper<CastMaterial> cqw = new QueryWrapper<>();
        cqw.eq("tech_id",entity.getTechId());
        List<CastMaterial> castMaterialList = castMaterialMapper.selectList(cqw);

        if ( castMaterialList != null && castMaterialList.size() !=0 ){
            CastMaterial castMaterial = castMaterialList.get(castMaterialList.size() - 1);
            int max = castMaterialList.stream().mapToInt(CastMaterial::getNumber).max().getAsInt();
            //如果本次生产没有结束，投料数没有被使用
            if (castMaterial.getIsUsed() == 0){
                entity.setIsUsed(0);
                entity.setNumber(castMaterial.getNumber());
                castMaterialMapper.insert(entity);
            }else {
                entity.setIsUsed(0);
                entity.setNumber(max+1);
                castMaterialMapper.insert(entity);
            }
        }else {
            entity.setIsUsed(0);
            entity.setNumber(1);
            castMaterialMapper.insert(entity);
        }

        return JsonResult.OK();
    }
}
